package com.yn.service.zy.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yn.common.enums.EnumZyOrderNoStr;
import com.yn.common.enums.EnumZyPayStatus;
import com.yn.common.exception.TransitException;
import com.yn.common.model.coupon.StoreCoupon;
import com.yn.common.model.user.UserAddress;
import com.yn.common.model.zy.DeviceRentOrderDO;
import com.yn.common.model.zy.DeviceRentOrderDetailDO;
import com.yn.common.model.zy.TDeviceInfoDO;
import com.yn.common.model.zyorder.ZyOrder;
import com.yn.common.page.BasePage;
import com.yn.common.request.sc.PageParamRequest;
import com.yn.common.request.zyorder.ZyDeviceRentOrderRequest;
import com.yn.common.utils.MoneyUtils;
import com.yn.common.utils.TransitUtils;
import com.yn.service.dao.zy.DeviceRentOrderMapper;
import com.yn.service.service.StoreCouponService;
import com.yn.service.service.UserAddressService;
import com.yn.service.service.UserService;
import com.yn.service.service.impl.ZyOrderServiceImpl;
import com.yn.service.zy.DeviceRentOrderService;
import com.yn.service.zy.model.dto.DeviceRentOrderDTO;
import com.yn.service.zy.model.query.DeviceRentOrderQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName: TDeviceRentOrderServiceImpl
 * @Description: 设备租赁订单ServiceImpl
 * @Author: ym
 * @Date: 2025/5/8 18:31
 **/
@Service
public class DeviceRentOrderServiceImpl extends ServiceImpl<DeviceRentOrderMapper, DeviceRentOrderDO> implements DeviceRentOrderService {

    @Resource
    private DeviceRentOrderMapper deviceRentOrderMapper;

    @Resource
    private TDeviceInfoServiceImpl tDeviceInfoService;
    @Resource
    private UserService userService;
    @Resource
    private  StoreCouponService storeCouponService;

    @Resource
    private   UserAddressService userAddressService;

    @Resource
    private   DeviceRentOrderDetailServiceImpl deviceRentOrderDetailServiceImpl;
    @Override
    public IPage<DeviceRentOrderDTO> listPage(DeviceRentOrderQuery query, BasePage basePage) {
        IPage<DeviceRentOrderDO> page = new Page(basePage.getPage(),basePage.getLimit());
        LambdaQueryWrapper<DeviceRentOrderDO> queryWrapper = new LambdaQueryWrapper<>();


        IPage<DeviceRentOrderDO> orderDOPage = deviceRentOrderMapper.selectPage(page, queryWrapper);

        return orderDOPage.convert(DeviceRentOrderDTO::transform);
    }

    @Override
    public String saveOrder(ZyDeviceRentOrderRequest request) {
        Integer userId = userService.getUserId();
        String orderNo = TransitUtils.getOrderNo(EnumZyOrderNoStr.ZP_DEVICE_ORDER.getCode()+userId);
        String deviceIds = request.getDeviceIds();
        Set<String> deviceIdSet = new HashSet<>();
        if (deviceIds != null && !deviceIds.isEmpty()) {
            String[] ids = deviceIds.split(",");
            Collections.addAll(deviceIdSet, ids);
        }
        if (deviceIdSet.isEmpty()) {
            throw new TransitException("设备信息不能为空,请选择设备!");
        }
        Integer rentDay = request.getRentDay();
        if (rentDay == null || rentDay <= 0) {
            throw new TransitException("租赁天数需大于0天!");
        }

        LambdaQueryWrapper<TDeviceInfoDO> tDeviceInfoDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tDeviceInfoDOLambdaQueryWrapper.in(TDeviceInfoDO::getId,deviceIdSet);
        List<TDeviceInfoDO> tDeviceInfoDOS = tDeviceInfoService.list(tDeviceInfoDOLambdaQueryWrapper);
        if (tDeviceInfoDOS.isEmpty()) {
            throw new TransitException("设备信息不存在!");
        }
       //设备租金总和
        Integer deviceRentAll = tDeviceInfoDOS.stream()
                .mapToInt(TDeviceInfoDO::getDeviceRent)
                .sum();
        deviceRentAll = deviceRentAll * rentDay;


        //计算设备押金总和
        Integer equipmentDepositAll  = tDeviceInfoDOS.stream()
                .mapToInt(TDeviceInfoDO::getEquipmentDeposit)
                .sum();

        //设备订单
        DeviceRentOrderDO deviceRentOrderDO = new DeviceRentOrderDO();
        deviceRentOrderDO.setAppUserId(userId);
        deviceRentOrderDO.setDeviceOrderNo(orderNo);

        Integer couponPrice = 0;
        Integer couponId = request.getCouponId();
        deviceRentOrderDO.setOrderPayPrice(deviceRentAll);
        Integer inspectionPayPrice=deviceRentAll;
        if (couponId != null) {
            StoreCoupon storeCoupon = storeCouponService.getById(couponId);
            if (storeCoupon == null) {
                throw new TransitException("所使用优惠券不存在!");
            }
            ZyOrderServiceImpl.checkCoupon(storeCoupon);
            BigDecimal money = storeCoupon.getMoney();
            couponPrice = MoneyUtils.yuan2fen(money);
            if (couponPrice > 0) {
                inspectionPayPrice=inspectionPayPrice-couponPrice;
                deviceRentOrderDO.setPreferentialPrice(couponPrice);
            }
        }
        deviceRentOrderDO.setInspectionPayPrice(inspectionPayPrice);
        deviceRentOrderDO.setCouponId(couponId);
        deviceRentOrderDO.setTotalNum(deviceIdSet.size());
        deviceRentOrderDO.setRentDay(rentDay);
        Integer userAddressId = request.getUserAddressId();
        UserAddress userAddress = userAddressService.getById(userAddressId);
        if (userAddress == null) {
            throw new TransitException("用户地址不存在!");
        }
        String province = userAddress.getProvince();
        String city = userAddress.getCity();
        String district = userAddress.getDistrict();
        String detail = userAddress.getDetail();
        String realName = userAddress.getRealName();
        String mobile = userAddress.getPhone();

        deviceRentOrderDO.setReceiveProvince(province);
        deviceRentOrderDO.setReceiveCity(city);
        deviceRentOrderDO.setReceiveDistrict(district);
        deviceRentOrderDO.setReceiveAddress(detail);
        deviceRentOrderDO.setReceiveName(realName);
        deviceRentOrderDO.setReceivePhone(mobile);
        deviceRentOrderDO.setPayStatus(EnumZyPayStatus.DFK.getCode());
        deviceRentOrderDO.setOrderStatus(EnumZyPayStatus.DFK.getCode());
        deviceRentOrderDO.setDepositMoney(equipmentDepositAll);
        this.save(deviceRentOrderDO);
        //设备订单详情保存
        List<DeviceRentOrderDetailDO>  deviceRentOrderDetailDOs= new ArrayList<>();
        tDeviceInfoDOS.forEach(tDeviceInfoDO -> {
            DeviceRentOrderDetailDO deviceRentOrderDetailDO = new DeviceRentOrderDetailDO();
            deviceRentOrderDetailDO.setDeviceId(tDeviceInfoDO.getId());
            deviceRentOrderDetailDO.setRentDay(rentDay);
            Integer deviceRent = tDeviceInfoDO.getDeviceRent();
            deviceRent=deviceRent*rentDay;
            deviceRentOrderDetailDO.setDeviceRent(deviceRent);
            deviceRentOrderDetailDO.setEquipmentDeposit(tDeviceInfoDO.getEquipmentDeposit());
            deviceRentOrderDetailDOs.add(deviceRentOrderDetailDO);
        });
        if (!deviceRentOrderDetailDOs.isEmpty()) {
            deviceRentOrderDetailServiceImpl.saveBatch(deviceRentOrderDetailDOs);
        }

        return orderNo;
    }

    @Override
    public BasePage<DeviceRentOrderDTO> listPage1(DeviceRentOrderQuery query, PageParamRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getLimit());
        LambdaQueryWrapper<DeviceRentOrderDO> queryWrapper = new LambdaQueryWrapper<>();
        List<DeviceRentOrderDO> deviceRentOrderDOS = baseMapper.selectList(queryWrapper);
        if(CollUtil.isEmpty(deviceRentOrderDOS)){
            return BasePage.restPage(new ArrayList<>());
        }
        BasePage<DeviceRentOrderDO> basePage = BasePage.restPage(deviceRentOrderDOS);
        ArrayList<DeviceRentOrderDTO> arrayList = new ArrayList<>(deviceRentOrderDOS.size());
        for (DeviceRentOrderDO deviceRentOrderDO : deviceRentOrderDOS) {
            arrayList.add(DeviceRentOrderDTO.transform(deviceRentOrderDO));
        }
        BasePage<DeviceRentOrderDTO> deviceRentOrderDTOBasePage = BasePage.restPage(arrayList);
        BeanUtils.copyProperties(basePage,deviceRentOrderDTOBasePage,"list");
        return deviceRentOrderDTOBasePage;
    }
}
